<% layout('/layouts/default.html', {title: '商户入驻', libs: ['validate','fileupload']}){ %>
<link rel="stylesheet" href="${ctxStatic}/icheck/1.0/square/blue.css?${_version}">
<link rel="stylesheet" href="${ctxStatic}/jquery-toastr/2.1/toastr.min.css?${_version}">
<link rel="stylesheet" href="${ctxStatic}/jquery-plugins/jquery.strength.css?${_version}">
<link rel="stylesheet" href="${ctxStatic}/modules/sys/sysLogin.css?${_version}">
<div class="login-box" style="margin:20px auto;">
	<div class="login-logo">
		<a href="${ctxPath}/a/sysLogin"><b>${@Global.getConfig('productName')}</b>
			<small>${@Global.getConfig('productVersion')}</small></a>
	</div>
	<div class="login-box-body">
		<form id="merchantForm">
			<div class="form-group has-feedback">
				<span class="fa fa-user form-control-feedback"></span>
				<input type="text" id="reg_name" name="name" class="form-control required" data-msg-required="请填写商户名称." placeholder="商户名称" />
			</div>
			<div class="form-group has-feedback">
				<span class="fa fa-info form-control-feedback"></span>
				<input type="text" id="reg_director" name="director" class="form-control required" data-msg-required="请填写负责人姓名." placeholder="负责人" />
			</div>
			<div class="form-group has-feedback reg-element reg-email">
				<span class="fa fa-envelope form-control-feedback"></span>
				<input type="text" id="reg_phone" name="phone" class="form-control required" data-msg-required="请填写联系方式." placeholder="联系方式" />
			</div>
			<div class="form-group has-feedback reg-element reg-email">
				<span class="fa fa-indent form-control-feedback"></span>
				<input type="text" id="reg_place" name="place" class="form-control required" data-msg-required="请填写商户地点." placeholder="商户地点" />
			</div>
			<div class="form-group has-feedback">
				<div class="col-sm-10 col-sm-9-8" style="margin-bottom: 10px;">
					<div class="custom-box">
						<div class="custom-center-title">
							<ul class="custom-ul" id="image"></ul>
							<div id="showBtn" class="custom-center">
								<i class="fa fa-image custom-icon"></i>
								<div class="custom-file">
									<span>点击选择图片</span>
									<input type="file" accept="image/*" class="cover-file" id="cover">
								</div>
								<span class="custom-tips">营业执照</span>
								<span class="custom-tips">最多可选择 1 张图片呦~</span>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="form-group has-feedback">
				<div class="col-sm-10 col-sm-9-8" style="margin-bottom: 10px;">
					<div class="custom-box">
						<div class="custom-center-title">
							<ul class="custom-ul" id="imageLogo"></ul>
							<div id="showBtn1" class="custom-center">
								<i class="fa fa-image custom-icon"></i>
								<div class="custom-file">
									<span>点击选择图片</span>
									<input type="file" accept="image/*" class="cover-file" id="logo">
								</div>
								<span class="custom-tips">logo</span>
								<span class="custom-tips">最多可选择 1 张图片呦~</span>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="row">
				<div class="col-xs-6">
					<button type="submit" class="btn btn-primary btn-block btn-flat"
						id="btnMerchantSubmit">${text('提交')}</button>
				</div>
				<div class="col-xs-6">
					<button type="button" class="btn btn-default btn-block btn-flat"
							id="btnReset">${text('返回')}</button>
				</div>
			</div>
			<div class="clearfix"></div>
		</form>
	</div>
</div>
<% } %>
<script src="${ctxStatic}/common/des.js?${_version}"></script>
<script src="${ctxStatic}/jquery-toastr/2.1/toastr.min.js?${_version}"></script>
<script src="${ctxStatic}/jquery-plugins/jquery.strength.js?${_version}"></script>
<script src="${ctxStatic}/jquery-plugins/jquery.strength_i18n.js?${_version}"></script>
<script src="${ctxStatic}/modules/sys/forgetPwd.js?${_version}"></script>
<script>
	let imgList = [],imgList1 = [];
	// 上传图片
	$('#cover').on('change', function (e) {
		let img = e.target.files;
		// 限制只能上传1张图片
		if (img.length > 1) {
			toastr.warning('最多只能选择1张图片！');
			return;
		}
		// 若已有图片，先清空（避免累积）
		if (imgList.length >= 1) {
			imgList = [];
		}
		const fix = (new Date()).getTime();
		for (let i = 0; i < img.length; i++) {
			const name = (img[i].name).split('.');
			const file = new File([img[i]], 'cover_' + (fix + i) + '.' + name[1]);
			file.imgType = 'new';
			imgList = imgList.concat(file);
		}
		imgShow(0, imgList);
	});

	// 显示图片列表
	function imgShow(index, attr) {
		let html = '';
		let windowURL = window.URL || window.webkitURL;
		for (let i = 0; i < attr.length; i++) {
			let dataURL = windowURL.createObjectURL(attr[i]);
			html += '<li class="custom-li">' +
					'<div class="custom-trash" onclick="removeImg(' + index + ',' + i + ')"><i class="fa fa-trash custom-del"></i></div>' +
					'<div><img class="custom-img" src="' + dataURL + '"></div>' +
					'<div class="custom-load">等待上传</div>' +
					'</li>';
			// 移除过早的 revoke，图片渲染后会自动释放，无需手动触发
			// windowURL.revokeObjectURL(attr[i]);
		}
		if (index == 0) {
			$('#showBtn').toggle(attr.length === 0); // 简化显示/隐藏逻辑
			$('#image').html(html);
		}else if(index == 1){
			$('#showBtn1').toggle(attr.length === 0); // 简化显示/隐藏逻辑
			$('#imageLogo').html(html);
		}
	}
	// 移除图片
	function removeImg(index, obj) {
		js.confirm('确认删除该图片吗？', function () {
			if (index == 0) {
				// 直接通过索引删除，无需遍历（优化逻辑）
				const target = imgList[obj];
				if (!target.imgType) {
					const img = target.split("/");
					deleteInfo.cover.push(img[img.length - 1]);
				}
				imgList.splice(obj, 1); // 从列表中删除
				imgShow(0, imgList);

				// 重置文件选择器（关键：清空value，确保下次选择能触发change事件）
				$('#cover').val('');
			}else if(index == 1){
				// 直接通过索引删除，无需遍历（优化逻辑）
				const target = imgList1[obj];
				if (!target.imgType) {
					const img = target.split("/");
					deleteInfo.cover.push(img[img.length - 1]);
				}
				imgList1.splice(obj, 1); // 从列表中删除
				imgShow(1, imgList1);

				// 重置文件选择器（关键：清空value，确保下次选择能触发change事件）
				$('#cover').val('');
			}
		});
	}

	// 上传图片
	$('#logo').on('change', function (e) {
		let img = e.target.files;
		// 限制只能上传1张图片
		if (img.length > 1) {
			toastr.warning('最多只能选择1张图片！');
			return;
		}
		// 若已有图片，先清空（避免累积）
		if (imgList1.length >= 1) {
			imgList1 = [];
		}
		const fix = (new Date()).getTime();
		for (let i = 0; i < img.length; i++) {
			const name = (img[i].name).split('.');
			const file = new File([img[i]], 'logo_' + (fix + i) + '.' + name[1]);
			file.imgType = 'new';
			imgList1 = imgList1.concat(file);
		}
		imgShow(1, imgList1);
	});

	$("#merchantForm").validate({
		submitHandler: function(form){
			let formData = $(form).serializeArray();
			saveFileData(formData);
		}
	});

	function saveFileData(formData) {
		if(imgList.length==0){
			js.showMessage('营业执照未上传！！');
			return;
		}
		if (imgList1.length==0){
			js.showMessage('logo图片未上传！！');
			return;
		}
		let paramsImg = new FormData();
		$.each(formData, function(i, obj) {
			paramsImg.append(obj.name,obj.value);
		});
		for(let i=0;i<imgList.length;i++){
			paramsImg.append('files',imgList[i]);
		}
		for(let i=0;i<imgList1.length;i++){
			paramsImg.append('files',imgList1[i]);
		}
		js.confirm('确认提交吗？', function(){
			$.ajax({
				url : '${ctx}/merchant/merchant/saveMerchantData',
				type : 'POST',
				data : paramsImg,
				dataType : 'JSON',
				contentType:false,
				processData:false,
				mimeType:"multipart/form-data",
				success : function(data) {
					// 显示消息提示（如“提交成功！”）
					js.showMessage(data.message);
					// 若提交成功，延迟1.5秒后返回上一页
					if(data.result == 'true'){
						setTimeout(() => {
							history.back(); // 延迟执行回退，确保用户看到提示
						}, 1500); // 1500毫秒=1.5秒
					}
				}
			});
		});
	}

</script>